package com.lottery.service.pc28.lobbyService.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lottery.dao.pc28.accoutDao.UserDao;
import com.lottery.entity.User;
import com.lottery.service.pc28.JedisClient;
import com.lottery.service.pc28.lobbyService.AccostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class AccostServiceImpl implements AccostService {
	@Autowired
	private JedisClient jedisClient;
	@Autowired
	private UserDao userDao;

	// @功能标志
	@Value("${TAG}")
	private String TAG;

	/**
	 * "@"功能 消息存储
	 * 
	 * @param senderId
	 *            发送方id
	 * @param receiveId
	 *            接收方id
	 * @param news
	 *            发送消息
	 * @return
	 */
	@Override
	public String setAccost(int senderId, int receiveId, String news) {
		JSONObject jObject = new JSONObject();
		User selectId = null;
		try {
			selectId = userDao.selectId(senderId);
		} catch (Exception e) {
			jObject.put("result", "1");
			jObject.put("msg", "userDao.selectId方法异常!");
			return jObject.toJSONString();
		}
		String body = senderId + ":-AITE-:" + selectId.getUserName() + ":-AITE-:" + selectId.getHeadPic() + ":-AITE-:"
				+ news;
		try {
			jedisClient.repush(TAG + receiveId, body);
			jObject.put("result", "0");
			jObject.put("msg", "存入成功");
		} catch (Exception e) {
			jObject.put("result", "1");
			jObject.put("msg", "存入redis服务器异常!");
		}
		return jObject.toJSONString();
	}

	/**
	 * "@"功能 消息拉取
	 * 
	 * @param receiveId
	 *            接收方id
	 * @return
	 */
	@Override
	public String getAccost(int receiveId) {
		Map<String, Object> maxmap = new HashMap<String, Object>();
		List<String> list = null;
		try {
			list = jedisClient.lrange(TAG + receiveId);
			if (list == null || list.size() == 0) {
				maxmap.put("result", "0");
				maxmap.put("msg", "暂时无消息");
				return JSON.toJSONString(maxmap, true);
			}
			jedisClient.del(TAG + receiveId);
		} catch (Exception e) {
			maxmap.put("result", "0");
			maxmap.put("msg", "取出redis服务器异常!");
			return JSON.toJSONString(maxmap, true);
		}
		ArrayList<Map<String, String>> listmap = new ArrayList<>();
		for (String string : list) {
			Map<String, String> map = new HashMap<>();
			String[] split = string.split(":-AITE-:");
			map.put("senderId", split[0]);
			map.put("senderName", split[1]);
			map.put("senderPic", split[2]);
			map.put("news", split[3]);
			listmap.add(map);
		}
		maxmap.put("array", listmap);
		maxmap.put("result", "0");
		return JSON.toJSONString(maxmap, true);
	}

}
